package im.youni.horus.core.recoder;
import im.youni.horus.core.SecondTag;
import im.youni.horus.core.common.Constants;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public final class RecordFactory {

    // 静态实例
    private static final RecordFactory instance = new RecordFactory();

    private ConcurrentMap<SecondTag, Recorder> reference;    // 指针引用
    private ConcurrentMap<SecondTag, Recorder> records1 = new ConcurrentHashMap<>(Constants.maxTagNum);
    private ConcurrentMap<SecondTag, Recorder> records2 = new ConcurrentHashMap<>(Constants.maxTagNum);

    private RecordFactory() {
        // empty
    }

    public static RecordFactory getInstance() {
        return instance;
    }

    /**
     * 获取指针引用地址
     * @return
     */
    public ConcurrentMap<SecondTag, Recorder> getReference() {
        if (reference == null) {
            reference = records1;
        }
        return reference;
    }

    /**
     * reference指针切换
     * @return
     */
    public synchronized ConcurrentMap<SecondTag, Recorder> changeReference() {
        if (records1.size() == 0 || records1.isEmpty()) {
            reference = records1;
            return records2;
        } else {
            reference = records2;
            return records1;
        }
    }

    /**
     * 生成或获取对应tag的recorder
     * @return
     */
    public Recorder getRecorder(SecondTag tag) throws Throwable {
        ConcurrentMap<SecondTag, Recorder> refer = getReference();
        Recorder recorder = refer.get(tag);
        if (recorder == null) {
            recorder = new AccurateRecorder(Constants.mostTimeThreshold, 0);
            refer.putIfAbsent(tag, recorder);
        }
        return recorder;
    }

}
